package drds.data_propagate.binlog_event;

import java.io.Closeable;
import java.io.IOException;
import java.util.Arrays;

/**
 * Declaration a binary-log fetcher. It extends from <code>Buffer</code>.
 *
 * <pre>
 * AbstractFetcher fetcher = new SomeLogFetcher();
 * ...
 *
 * while (fetcher.fetchNextBinlogEvent())
 * {
 *     BinLogEvent binlog_event;
 *     do
 *     {
 *         binlog_event = decoder.$(fetcher, context);
 *
 *         // process log binlog_event.
 *     }
 *     while (binlog_event != null);
 * }
 * // no more binlog_event.
 * fetcher.close();
 * </pre>
 */

public abstract class AbstractPacketReader extends Buffer implements Closeable {

    public static final int default_initial_capacity = 8192;
    public static final float default_growth_factor = 2.0f;
    public static final int bin_log_header_size = 4;

    protected final float growthFactor;

    public AbstractPacketReader() {
        this(default_initial_capacity, default_growth_factor);
    }

    public AbstractPacketReader(final int initialCapacity) {
        this(initialCapacity, default_growth_factor);
    }

    public AbstractPacketReader(final int initialCapacity, final float growthFactor) {
        this.bytes = new byte[initialCapacity];
        this.growthFactor = growthFactor;
    }

    /**
     * 如果当前的容量不足,根据增长因子进行扩容
     */
    protected final void ensureCapacity(final int minCapacity) {
        final int oldCapacity = bytes.length;
        if (minCapacity > oldCapacity) {
            int newCapacity = (int) (oldCapacity * growthFactor);
            if (newCapacity < minCapacity) {
                newCapacity = minCapacity;
            }
            bytes = Arrays.copyOf(bytes, newCapacity);
        }
    }

    public abstract boolean fetchNextBinlogEvent() throws IOException;

    public abstract void close() throws IOException;
}
